package com.qingke.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private String driverStr="com.mysql.jdbc.Driver";
	private String connStr="jdbc:mysql://localhost:3306/servlet_login?useUnicode=true&characterEncoding=utf-8&useSSL=false";
	private String sqlUsername="zjy";
	private String sqlPassword="123456";
	
    private Connection conn=null;		
    private String sql;
    private PreparedStatement ps=null;
    private ResultSet rs=null;  
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

    
	@Override
	public void init() throws ServletException {
		super.init();
		try {
			Class.forName(driverStr);
			conn = DriverManager.getConnection(connStr,sqlUsername,sqlPassword);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}


	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		sql="select * from user where username=? and password=?;";
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1,username);
			ps.setString(2,password);
			rs=ps.executeQuery();
			if(rs!=null){
				if(rs.next()){
					request.getSession().setAttribute("username",username);
					request.getSession().setAttribute("password",password);
					request.getSession().setAttribute("logged",new Integer(1));
//					response.getWriter().append("login success.");
					response.sendRedirect("upload.jsp");
				}
				else{
					throw new ServletException();
				}
			}
			else{
				throw new ServletException();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new ServletException();
		}
		
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
